package com.example.journalegocentrique;

import java.io.IOException;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap; 


import com.example.journalegocentrique.R.drawable;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.media.ThumbnailUtils;
import android.preference.PreferenceManager;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ExpandableListAdapter;

@SuppressLint({ "SdCardPath", "SimpleDateFormat" })
public class SampleExpandableListAdapter extends BaseExpandableListAdapter implements ExpandableListAdapter  {
       public Context context;
       CheckBox checkBox;
   private LayoutInflater vi;
   private String[][] data;
   int _objInt;
   public static Boolean checked[] = new Boolean[1];

   HashMap<Long,Boolean> checkboxMap = new HashMap<Long,Boolean>();
   private static final int GROUP_ITEM_RESOURCE = R.layout.activity_row_item;
   private static final int CHILD_ITEM_RESOURCE = R.layout.activity_row_entry_item;
   private static final int CHILD_ITEM_RESOURCE_1 = R.layout.activity_row_entry_item_1;
   public String []check_string_array;
  
   public SampleExpandableListAdapter(Context context, Activity activity, String[][] data) {
       this.data = data;
       this.context = context;
       vi = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
      
       _objInt = data.length;
       check_string_array = new String[_objInt];
       popolaCheckMap();
   }
   
   
   public void popolaCheckMap(){

       SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context); 
       String buffer = null;
      
       for(int i=0; i<_objInt; i++){
               buffer = settings.getString(String.valueOf((int)i),"false");
               if(buffer.equals("false"))
                       checkboxMap.put((long)i, false);
               else checkboxMap.put((long)i, true);
       }
   }
  
   public class CheckListener implements OnCheckedChangeListener{

       long pos;

       public void setPosition(long p){
           pos = p;
       }

       @Override
       public void onCheckedChanged(CompoundButton buttonView,
               boolean isChecked) {
               Log.i("checkListenerChanged", String.valueOf(pos)+":"+String.valueOf(isChecked));
           checkboxMap.put(pos, isChecked);
           if(isChecked == true) check_string_array[(int)pos] = "true";
           else                                  check_string_array[(int)pos] = "false";
          // save checkbox state of each group
           SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);                
           SharedPreferences.Editor preferencesEditor = settings.edit();
           preferencesEditor.putString(String.valueOf((int)pos), check_string_array[(int)pos]);
           preferencesEditor.commit();
       }
   }
   public String getChild(int groupPosition, int childPosition) {
       return data[groupPosition][childPosition];
   }

   public long getChildId(int groupPosition, int childPosition) {
       return childPosition;
   }

   public int getChildrenCount(int groupPosition) {
       return data[groupPosition].length;
   }

   public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
       View v = convertView;
       String child = getChild(groupPosition, childPosition);
       
       if (child != null) {
    	   v = vi.inflate(CHILD_ITEM_RESOURCE, null);
           ViewHolder holder = new ViewHolder(v);
           String childC=Html.fromHtml(child).toString();
           String[] split=new String[10];
           split=childC.split("~");
           String data = UtilityDB.getDayFromId(Integer.parseInt(split[4]));
           String[] splitData2 = data.split("-");
           data = splitData2[2] + "/"+splitData2[1]+"/"+splitData2[0];
           Date dataEng = new Date(data);
           SimpleDateFormat sdf2 = new SimpleDateFormat("EEE dd MMMM yyyy");
           String strData = sdf2.format(dataEng); // data con giorno e mese in lettere
           String[] splitData = strData.split(" ");
           String emo=split[2];
           int drawableId=0;
           try
           {
        	    Class<drawable> res = R.drawable.class;
        	    Field field = res.getField(emo);
        	    drawableId = field.getInt(null);
           }
           catch (Exception e) {
        	    Log.e("Percorso immagine", "Failure to get drawable id.", e);
        	}
           //for(i=0;i<getChildrenCount(groupPosition);i++)
           //{
        	   holder.hourE.setText(split[1]); //ora
        	   if (!split[3].equals("null")){
        		   holder.nota.setText(split[3]); //nota
        		   holder.imageTrian.setImageResource(R.drawable.triangolo);
        	   }
        	   holder.day_lettersE.setText(splitData[0]);
        	   holder.dayE.setText(splitData[1]);
        	   holder.imageviewE.setImageResource(drawableId);
        	   String place = UtilityDB.getPlaceFromIdEntry(Integer.parseInt(split[0]));
        	   if ( place != null){
        		   holder.place.setText(Html.fromHtml("<i>" + place
							+ "</i>"));
        	   }
           //}
       }
       else
       {
    	   v = vi.inflate(CHILD_ITEM_RESOURCE_1, null);
           ViewHolderEmpty holder_vuoto = new ViewHolderEmpty(v);
           holder_vuoto.text_vuoto.setText("Nessuna nota salvata");
       }
       return v;
   }
   public String getGroup(int groupPosition) {
       return "group-" + groupPosition;
   }
   public int getGroupCount() {
       return data.length;
   }
   public long getGroupId(int groupPosition) {
       return groupPosition;
   }
   public static long getGroupIdStatic(int groupPosition) {
       return groupPosition;
   }
   public void removeChild(int group, int child) {
       //TODO: Remove the according child
       Log.v("Adapter", "Removing child "+child+" in group "+group);
       notifyDataSetChanged();
   }
   public static int getIdDay(int groupPosition){
	   int idDay = 0;
	   long group_id = getGroupIdStatic(groupPosition);
	   SQLiteDatabase database = GetDataBase.getDb();
       String query = "SELECT * FROM tbDay ORDER BY _id DESC";	
       Cursor cursor = null;	
       cursor = database.rawQuery(query, null);
       int i=0;
		while (cursor.moveToNext()) {
			if(group_id==i)
				idDay = cursor.getInt(0);
			group_id = getGroupIdStatic(groupPosition);
			i++;
		}
		cursor.close();
	   return idDay;
   }
   
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
       View v = convertView;
       String group = null;
       long group_id = getGroupId(groupPosition);
       SQLiteDatabase database = GetDataBase.getDb();
       String query = "SELECT * FROM tbDay ORDER BY _id DESC";		
      
       Cursor cursor = null;		
       Cursor cursor2 = null;
       cursor = database.rawQuery(query, null);
       
       int numEntry =0;
       int i=0;
		while (cursor.moveToNext()) {
			if(group_id==i)
			{
				String query2 = "SELECT count(*) AS tot, idDay FROM tbEntry WHERE idDay ="+Integer.parseInt(cursor.getString(0))+" GROUP BY idDay";
				cursor2 = database.rawQuery(query2, null);
				String data = cursor.getString(1);
				String[] splitData2 =data.split("-");
				data = splitData2[2] + "/"+splitData2[1]+"/"+splitData2[0];
				String photo = cursor.getString(2);
				String hour = cursor.getString(3);
				group= cursor.getString(0);
				Date dataEng = new Date(data);
				if(group!=null)
				{
					v=vi.inflate(GROUP_ITEM_RESOURCE, null);	
					ViewHolder holder=new ViewHolder(v);
					if (cursor2.moveToNext())
						numEntry = cursor2.getInt(0);
					SimpleDateFormat sdf2 = new SimpleDateFormat("EEEE dd MMMM yyyy");
					String strData = sdf2.format(dataEng); // data con giorno e mese in lettere
					String[] splitData = strData.split(" ");
					holder.text.setText(splitData[1]);
					holder.month.setText((splitData[2]+" "+splitData[3]).toUpperCase());
					holder.day_letters.setText(splitData[0]);
					holder.text2.setText(hour);
					if (numEntry == 1)
						holder.numEntry.setText(""+numEntry+ " nota");
					else
						holder.numEntry.setText(""+numEntry+ " note");
					Bitmap bmp1;
					Bitmap b1=null;
					//holder.imageview.setImageURI(null);
					//holder.imageview.setImageURI(Uri.fromFile(new File("/mnt/storage/default_avatar.jpg")));
					if (photo != null){
						try {
							bmp1 = OrientationPicture.changeOrientation(photo);
							b1 = ThumbnailUtils.extractThumbnail(bmp1, 140, 200);
							
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();									
						}	
						if(b1!=null)
							holder.imageview.setImageBitmap(b1);
						else
							holder.imageview.setImageResource(R.drawable.default_avatar);
					}
					else
						holder.imageview.setImageResource(R.drawable.default_avatar);
				}
				cursor2.close();
			}
			group_id = getGroupId(groupPosition);
			i++;
		}
		cursor.close();
		database.close();
		
        return v;
   }
   public boolean isChildSelectable(int groupPosition, int childPosition) {
       return true;
   }
   public boolean hasStableIds() {
       return true;
   }
} 
